package com.eternal.base;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import com.eternal.base.concat.BluetoothEvent;
import com.eternal.base.data.RepositoryInjection;
import com.eternal.framework.bus.RxBus;
import com.eternal.framework.utils.KLog;

import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.CompletableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class BluetoothStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
            int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
            if (blueState == BluetoothAdapter.STATE_OFF) {
                KLog.w("蓝牙已关闭");
                postEvent(BluetoothEvent.STATE_OFF);
                RepositoryInjection.providerDeviceRepository().disableBle();
            } else if (blueState == BluetoothAdapter.STATE_ON) {
                KLog.w("蓝牙已开启");
                postEvent(BluetoothEvent.STATE_ON);
            }
        }
    }

    private void postEvent(final byte what) {
        Completable.create(new CompletableOnSubscribe() {
            @Override
            public void subscribe(CompletableEmitter emitter) throws Exception {
                RxBus.getDefault().post(new BluetoothEvent(what,0));
            }
        }).subscribeOn(AndroidSchedulers.mainThread()).subscribe();
    }
}
